﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _07_Lock锁
{
    /// <summary>
    /// 账户余额
    /// </summary>
    class Account
    {
        public int Balance { get; set; }

        public Account(int balance)
        {
            this.Balance = balance;
        }
        /// <summary>
        /// 取款
        /// </summary>
        /// <param name="name">取款人</param>
        /// <param name="amount">金额</param>
        public void WithDraw(string name,int amount)
        {
            lock (this)
            {
                //判断余额是否足够
                if (this.Balance >= amount)
                {
                    //模拟取款需要的时间
                    Thread.Sleep(1000);
                    //更新余额
                    this.Balance -= amount;
                    //提示取款成功
                    Console.WriteLine(name + "取款成功，余额为：" + this.Balance);
                }
                else
                {
                    Console.WriteLine(name + "余额不足，取款失败！");
                }                
            }


        }

    }

    internal class Program
    {
        static void Main(string[] args)
        {
            //创建账户，余额为1000
            Account account = new Account(1000);
            //创建两个线程，模拟两个人同时取款
            new Thread(() => account.WithDraw("小明", 800)) { IsBackground=true}.Start();
            new Thread(() => account.WithDraw("小红", 800)) { IsBackground = true }.Start();

            Console.Read();
        }
    }
}
